package com.tzy.note.base.thread;

import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author tangzanyong
 * @description 多线程实现方式五：线程池ExecutorService
 *      ExecutorService线程管理工具
 * @date 2020/4/16
 **/
public class Thread5{

    @Test
    public void test() throws Exception{
        int taskSize = 5;
        //1 创建一个线程池
        // 调用Executors类的静态方法(并初始化线程的数量)
        ExecutorService threadPool = Executors.newFixedThreadPool(taskSize);
        for (int i = 0; i < taskSize; i++) {
            //2 提交runnable对象，提交多个线程任务，并执行
            threadPool.submit(new Runnable() { //不需要返回值也可以把submit -> execute
                @Override
                public void run() {
                    String task = Thread.currentThread().getName() + "执行任务...";
                    System.out.println(task);
                }
            });
        }
        // 关闭线程池
        threadPool.shutdown();
    }

}
